package controller

import (
	"log"
	"testhttp/dao"
	"testhttp/model"
	"testhttp/service"

	"github.com/kataras/iris/v12"
)

func ListDealer(ctx iris.Context) {
	var params model.HttpParamsDealer
	err := ctx.ReadJSON(&params)
	if err != nil && !iris.IsErrPath(err) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.WriteString(err.Error())
		log.Print("[Debug] ListDealer():", err)
	} else {
		res := service.ListDealer(params)
		ctx.JSON(res)
		log.Print("Debug res:", res)
	}
}

func ImportDealer(ctx iris.Context) {
	var dealer []model.Dealer
	var querydata []model.Dealer
	z := 0 //有效计数
	err := ctx.ReadJSON(&dealer)
	if err != nil && !iris.IsErrPath(err) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.WriteString(err.Error())
	} else {
		for x := 0; x < len(dealer); x++ {
			switch {
			case dealer[x].Dealer == "":
				log.Print("Error: Dealer is null!")
			case dealer[x].Shop == "":
				log.Print("Error: Shop is null!")
			case dealer[x].ShipConditions == "":
				log.Print("Error: ShipConditions is null!")
			case dealer[x].OrderType == "":
				log.Print("Error: OrderType is null!")
			default:
				querydata = append(querydata, dealer[x])
				z++
			}
		}
		ctx.JSON(service.AddDealer(querydata))
	}
}

func AddDealer(ctx iris.Context) {
	var dealer []model.Dealer

	err := ctx.ReadJSON(&dealer)
	if err != nil && !iris.IsErrPath(err) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.WriteString(err.Error())
	} else {
		ctx.JSON(service.AddDealer(dealer))
	}
}

func DelDealer(ctx iris.Context) { //逻辑删除
	var dealer []model.Dealer

	err := ctx.ReadJSON(&dealer)
	if err != nil && !iris.IsErrPath(err) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.WriteString(err.Error())
	} else {
		for x := 0; x < len(dealer); x++ {
			dealer[x].IsDeleted = 1
		}
		ctx.JSON(service.UpdateDealer(dealer))
	}

}

func ViewDealer(ctx iris.Context) {
	id := ctx.URLParam("id")

	ctx.JSON(dao.ViewDealer(id))
}

func UpdateDealer(ctx iris.Context) {
	var dealer []model.Dealer
	err := ctx.ReadJSON(&dealer)

	if err != nil && !iris.IsErrPath(err) {
		ctx.StatusCode(iris.StatusInternalServerError)
		ctx.WriteString(err.Error())
		log.Print("Debug UpdateDealer():", err)
	} else {
		ctx.JSON(service.UpdateDealer(dealer))
	}

}
